<?php
namespace app\lateCoach\controller;
use app\common\Base;
use app\common\Compent;
use app\common\Excel;
use think\Db;

class LateCoachTotal extends Base {
	
	public function index() {
		return $this->fetch();
	}

	public function pageQuery() {
		$result = $this::getData();
		$grid["rows"] = $result;
		$grid["total"] = count($result);
		return $grid;
	}

	public function exportExcel() {
		$data = $this::getData();
		//excel表头内容
		$header = array("年级"=>"grade","教师姓名"=>"teacherName","是否班主任"=>"classTeacher","周一(次)"=>"d1Count","周二(次)"=>"d2Count","周三(次)"=>"d3Count","周四(次)"=>"d4Count","第八节(次)"=>"d8Count","总数(次)"=>"totalCount");
		Excel::toExcel($data,'晚修辅导统计',$header);
		exit;
	}

	public function getData() {
		$startDate = input("startDate");
		$endDate = input("endDate");
		$sql = "select js.ID teacherId,a.teacherName,isnull(week, 0) week,
		isnull(weekCount, 0) weekCount, bz.班主任ID bzId, js.年级号 grade,js.学籍类型 studyType 
		from 教师信息 js
		inner join (
			select TEACHER_NAME teacherName
			from T_LATE_COACH_PLAN
			group by TEACHER_NAME
		) a on a.teacherName = js.姓名
		left join (
			 select 
			 TEACHER_NAME teacherName, 
			 WEEK week, 
			 COUNT(1) weekCount
			 from T_LATE_COACH_REGISTER
			 where IS_VALID = 1 and COACH_TYPE in (2,3)
			 	and convert(varchar(12),CREATE_TIME,23) between ".$startDate." and ".$endDate." 
			 group by TEACHER_NAME, WEEK
			 union all
			 select 
			 TEACHER_NAME teacherName, 
			 8 week, 
			 COUNT(1) weekCount
			 from T_LATE_COACH_REGISTER
			 where IS_VALID = 1 and COACH_TYPE = 1
			 	and convert(varchar(12),CREATE_TIME,23) between ".$startDate." and ".$endDate."
			 group by TEACHER_NAME
		) b on b.teacherName = a.teacherName
		left join 班主任科任 bz on bz.班主任ID = js.ID
		order by js.年级号 desc, teacherName, week";
		$data = Db::query($sql);
		$result = [];
		foreach ($data as $key => $obj) {
			if(!array_key_exists($obj["teacherId"], $result)) {
				$v = [];
				$v["teacherId"] = $obj["teacherId"];
				$v["teacherName"] = $obj["teacherName"];
				$v["grade"] = getGradeName($obj["grade"],$obj["studyType"]);
				$v["classTeacher"] = $obj["bzId"] ? "是" : "否";
				$v["totalCount"] = 0;
				$result[$obj["teacherId"]] = $v;
			}
			$v = $result[$obj["teacherId"]];
			if($obj["week"] == 1) $v["d1Count"] = $obj["weekCount"];
			else if($obj["week"] == 2) $v["d2Count"] = $obj["weekCount"];
			else if($obj["week"] == 3) $v["d3Count"] = $obj["weekCount"];
			else if($obj["week"] == 4) $v["d4Count"] = $obj["weekCount"];
			else if($obj["week"] == 5) $v["d5Count"] = $obj["weekCount"];
			else if($obj["week"] == 6) $v["d6Count"] = $obj["weekCount"];
			else if($obj["week"] == 7) $v["d7Count"] = $obj["weekCount"];
			else if($obj["week"] == 8) $v["d8Count"] = $obj["weekCount"];
			$count = $v["totalCount"];
			$count += $obj["weekCount"];
			$v["totalCount"] = $count;
			$result[$obj["teacherId"]] = $v;
		}
		$data = [];
		foreach ($result as $key => $value) {
			array_push($data, $value);
		}
		return $data;
	}

}
